package org.thanos.simulator.page;

import org.eclipse.paho.client.mqttv3.MqttException;
import org.thanos.simulator.api.MQTTClientApi;
import org.thanos.simulator.page.network.NetworkConfigPage;
import org.thanos.simulator.page.topic.TopicPage;

import javax.swing.*;
import java.awt.*;
import java.util.Objects;

public class IndexPage {

    private final JFrame jFrame;

    public IndexPage() {
        jFrame = new JFrame("MQTT Connect 模拟器");
        jFrame.setSize(600, 400);
        jFrame.setDefaultCloseOperation(jFrame.EXIT_ON_CLOSE);// 设置关闭退出
        jFrame.setLayout(new BorderLayout());
        jFrame.setVisible(true);
        this.reloadMenu();
    }

    /**
     * build menu
     *
     * @return
     */
    private JMenuBar configMenuBar() {
        JMenuBar menuBar = new JMenuBar();
        JMenu menu1 = new JMenu("文件");
        menuBar.add(menu1);
        JMenuItem networkMenu = new JMenuItem("创建连接");
        networkMenu.setEnabled(!MQTTClientApi.isInitialized());
        networkMenu.addActionListener(e -> SwingUtilities.invokeLater(() -> {
            new NetworkConfigPage(this);
        }));
        JMenuItem topicMenu = new JMenuItem("添加Topic");
        topicMenu.setEnabled(MQTTClientApi.isInitialized());
        topicMenu.addActionListener(e -> SwingUtilities.invokeLater(() -> {
            new TopicPage(this);
        }));
        JMenuItem stopMenu = new JMenuItem("断开");
        stopMenu.setEnabled(MQTTClientApi.isInitialized());
        stopMenu.addActionListener(e -> SwingUtilities.invokeLater(() -> {
            int result = JOptionPane.showConfirmDialog(null, "是否断开网络？");
            if (result == JOptionPane.YES_OPTION) {
                try {
                    MQTTClientApi.disconnected();
                    JOptionPane.showMessageDialog(null, "断开成功！");
                    this.reloadMenu();
                } catch (MqttException ex) {
                    JOptionPane.showMessageDialog(null, ex.getMessage());
                    ex.printStackTrace();
                }
            }
        }));
        menu1.add(networkMenu);
        menu1.add(topicMenu);
        menu1.add(stopMenu);
        return menuBar;
    }


    public void reloadMenu() {
        if (Objects.nonNull(jFrame.getJMenuBar())) {
            jFrame.remove(jFrame.getJMenuBar());
        }
        jFrame.setJMenuBar(this.configMenuBar());
        jFrame.repaint();
        jFrame.setVisible(true);
    }
}
